<?php
declare (strict_types=1);

namespace app\admin\controller\media;

use app\common\controller\BaseController;
use app\admin\model\media\Website as WebsiteModel;

use think\exception\ValidateException;

class Website extends BaseController
{

    protected $noNeedRight = ['allWebsite'];

    /**
     * @var WebsiteModel
     */
    protected $model;

    public function initialize()
    {
        parent::initialize();

        $this->model = new WebsiteModel;
    }

    public function edit($id = null)
    {
        $row = $this->model->find($id);
        if (!$row) {
            return $this->error(lang('No Results were found'));
        }
        if ($this->request->isPut()) {
            $params = $this->request->put();
            if ($params) {
                //模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    try {
                        $this->validate($params, $validate);
                        $validateRes = true;
                    } catch (ValidateException $e) {
                        // 验证失败 输出错误信息
                        $validateRes = $e->getError();
                    }
                    if ($validateRes !== true) {
                        return $this->error($validateRes);
                    }
                }
                $old = $row['group_id'];
                $new = $params['group_id'];

                $result = $row->save($params);
                if ($result !== false) {
                    $row->changeMoudleGroup($new,$old);
                    return $this->success('编辑成功');
                } else {
                    return $this->error(lang('No rows were updated'));
                }
            }
            return $this->error(lang('Parameter %s can not be empty', ''));
        }
    }

    public function allWebsite()
    {
        $filter = $this->request->param();

        $where = function ($query) use ($filter) {
            if (isset($filter['group_id'])) {
                $query->where('group_id', '=', $filter['group_id']);
            }
        };
        $list = $this->model->field('id,name')
            ->where($where)
            ->where('status', '=', 1)
            ->order(['weigh' => 'desc', 'id' => 'asc'])
            ->select();

        return $this->success('请求成功',$list);
    }

}